package com.insurance.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.insurance.common.common.ResponseData;
import com.insurance.common.constant.ConstantFlag;
import com.insurance.common.dto.*;
import com.insurance.common.enums.CommonEnum;
import com.insurance.common.enums.DeleteFlagEnum;
import com.insurance.common.utils.JwtOperatorUtil;
import com.insurance.common.utils.NumberUtils;
import com.insurance.entity.AuthenticationEnterpriseEntity;
import com.insurance.entity.OrderEntity;
import com.insurance.entity.ProposalEntity;
import com.insurance.product.entity.ProductEntity;
import com.insurance.product.service.ProductService;
import com.insurance.productcase.entity.ProductCaseEntity;
import com.insurance.productcase.service.ProductCaseService;
import com.insurance.service.AuthenticationEnterpriseService;
import com.insurance.service.OrderService;
import com.insurance.service.ProposalService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Style
 * @version 1.0
 * @date 2021/3/10
 **/
@Api(tags = "订单服务")
@Slf4j
@RestController
@RequestMapping("/order")
public class BodyOrderController {

    //region 注入类

    /**
     * 订单service
     */
    @Autowired
    private OrderService orderService;

    /**
     * 投保单service
     */
    @Autowired
    private ProposalService proposalService;

    /**
     * 产品service
     */
    @Autowired
    private ProductService productService;

    /**
     * 方案service
     */
    @Autowired
    private ProductCaseService productCaseService;

    /**
     * 企业信息service
     */
    @Autowired
    private AuthenticationEnterpriseService authenticationEnterpriseService;

    //endregion

    //region 分页查询订单列表

    /**
     * 分页查询订单列表
     *
     * @param pageOrderDto 查询条件
     * @param userToken 用户凭证
     * @return
     */
    @ApiOperation(value = "分页查询订单列表")
    @PostMapping("/queryOrderPage")
    public ResponseData<Page<OrderDto>> queryOrderPage(@RequestBody PageOrderDto pageOrderDto, @RequestHeader(value = "Authorization") String token, @RequestHeader String userToken){
        String userId = "";
        try {
            //校验用户凭证
            if(!JwtOperatorUtil.validateToken(userToken)){
                log.error("【查询订单列表失败, 用户凭证错误】");
                return ResponseData.error(CommonEnum.USER_TOKEN_ERROR);
            }
            //获取用户主键
            userId = JwtOperatorUtil.getUserId(userToken);
            if(StringUtils.isBlank(userId)){
                log.error("【查询订单列表失败, 用户为空】");
                return ResponseData.success(CommonEnum.USER_TOKEN_ERROR);
            }
            Page page = new Page(pageOrderDto.getCurrent(), pageOrderDto.getSize());
            OrderEntity orderEntity = new OrderEntity();
            orderEntity.setOrderState(pageOrderDto.getOrderState());
            orderEntity.setOrderId(pageOrderDto.getOrderId());
            orderEntity.setCreatePersonId(userId);
            orderEntity.setProductId(pageOrderDto.getProductId());
            //分页查询订单
            Page<OrderDto> orderPageInfo = orderService.queryOrderDtoPage(page, orderEntity);
            List<OrderDto> orderDtoList = orderPageInfo.getRecords();
            if(CollectionUtils.isNotEmpty(orderDtoList)){
                orderDtoList.forEach(orderDto -> {
                    if(orderDto.getProposalId() != null){
                        ProposalEntity proposalEntity = proposalService.getById(orderDto.getProposalId());
                        if(proposalEntity != null){
                            ProposalDto proposalDto = new ProposalDto();
                            BeanUtils.copyProperties(proposalEntity, proposalDto);
                            orderDto.setProposalDto(proposalDto);
                        }
                    }
                });
            }
            return ResponseData.success(orderPageInfo);
        } catch (Exception e) {
            log.error("【用户：{}, 查询订单列表失败, 系统异常：{}】", userId, e);
            return ResponseData.error(CommonEnum.SYSTEM_ERROR);
        }
    }
    //endregion

    //region 通过订单Id查询订单详情

    /**
     * 通过订单Id查询订单详情
     *
     * @param orderFormDto 订单主键
     * @return
     */
    @ApiOperation(value = "通过订单Id查询订单详情")
    @PostMapping("/getOrderDetail")
    public ResponseData<OrderDto> getOrderDetail(@RequestBody OrderFormDto orderFormDto, @RequestHeader(value = "Authorization") String token){
        try {
            if(StringUtils.isBlank(orderFormDto.getOrderId())){
                log.error("【通过订单Id查询订单详情失败, 订单id不能为空】");
                return ResponseData.error(CommonEnum.QUERY_ERROR_NODATA);
            }
            //通过主键查询订单
            OrderEntity order = orderService.getById(orderFormDto.getOrderId());
            if(order == null){
                log.error("【订单Id：{}, 通过主键查询订单失败, 订单不存在】", orderFormDto.getOrderId());
                return ResponseData.error(CommonEnum.QUERY_ERROR_NODATA);
            }
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(order, orderDto);
            //通过投保单id查询投保单
            ProposalEntity proposalEntity = proposalService.getById(order.getProposalId());
            if(proposalEntity == null){
                log.error("【订单Id：{}, 通过主键查询订单失败, 投保单不存在】", orderFormDto.getOrderId());
                return ResponseData.error(CommonEnum.QUERY_ERROR_NODATA);
            }
            ProposalDto proposalDto = new ProposalDto();
            BeanUtils.copyProperties(proposalEntity, proposalDto);
            orderDto.setProposalDto(proposalDto);
            try {
                //获取投保人id
                String applyUserId = proposalDto.getApplyUserId();
                if(!StringUtils.isBlank(applyUserId)){
                    //通过企业id查询企业信息
                    AuthenticationEnterpriseEntity enterpriseEntity = authenticationEnterpriseService.getById(applyUserId);
                    AuthenticationEnterpriseDto authenticationEnterpriseDto = new AuthenticationEnterpriseDto();
                    if(enterpriseEntity != null){
                        BeanUtils.copyProperties(enterpriseEntity, authenticationEnterpriseDto);
                        proposalDto.setEnterprise(authenticationEnterpriseDto);
                    }
                }
            } catch (Exception e) {
                log.info("【订单Id：{}, 通过主键查询订单未发现企业信息】", orderFormDto.getOrderId(), e);
            }
            return ResponseData.success(orderDto);
        } catch (Exception e) {
            log.error("【订单Id：{}, 通过主键查询订单失败, 系统异常】", orderFormDto.getOrderId(), e);
            return ResponseData.error(CommonEnum.SYSTEM_ERROR);
        }
    }
    //endregion

    //region 保存订单

    /**
     * 保存订单
     *
     * @param orderFormDto
     * @return
     */
    @ApiOperation(value = "保存订单")
    @PostMapping("/saveOrder")
    public ResponseData saveOrder(@RequestBody OrderFormDto orderFormDto, @RequestHeader(value = "Authorization") String token, @RequestHeader String userToken){
        try {
            if(!JwtOperatorUtil.validateToken(userToken)){
                return ResponseData.error(CommonEnum.USER_TOKEN_ERROR);
            }
            OrderEntity orderEntity = new OrderEntity();
            BeanUtils.copyProperties(orderFormDto, orderEntity);
            String checkOrder = checkOrder(orderEntity);
            if(!ConstantFlag.TRUE_STR.equals(checkOrder)){
                log.error("【保存订单失败, {}】", checkOrder);
                return ResponseData.error(checkOrder);
            }
            String appId = JwtOperatorUtil.getAppId(token);
            String userId = JwtOperatorUtil.getUserId(userToken);
            String cardId = JwtOperatorUtil.getCardId(userToken);
            orderEntity.setCreateTime(new Date());
            orderEntity.setAppId(appId);
            orderEntity.setCardId(cardId);
            orderEntity.setCreatePersonId(userId);
            orderEntity.setDeleteFlag(String.valueOf(DeleteFlagEnum.UN_DELETE.getCode()));
//        orderEntity.setOrderState(OrderStateEnum.NO_PAY.getCode());
            boolean flag = orderService.save(orderEntity);
            return flag ? ResponseData.success(String.valueOf(orderEntity.getOrderId())) : ResponseData.error(CommonEnum.SAVE_ERROR);
        } catch (BeansException e) {
            log.error("【保存订单失败, 系统异常】", e);
            return ResponseData.error(CommonEnum.SYSTEM_ERROR);
        }
    }
    //endregion

    //region 通过订单Id修改订单状态

    /**
     * 通过订单Id修改订单状态
     *
     * @param orderStateDto 订单对象
     * @return
     */
    @ApiOperation(value = "通过订单Id修改订单状态")
    @PostMapping("/changeOrderState")
    public ResponseData changeOrderState(@RequestBody OrderStateDto orderStateDto, @RequestHeader(value = "Authorization") String token){
        if(orderStateDto.getOrderId() == null){
            return ResponseData.error("订单id不能为空");
        }
        if(StringUtils.isBlank(orderStateDto.getState())){
            return ResponseData.error("订单状态不能为空");
        }
        //通过订单id查询订单对象
        OrderEntity order = orderService.getById(orderStateDto.getOrderId());
        if(order == null){
            log.error("【订单Id：{}, 通过主键查询订单失败, 订单不存在】", orderStateDto.getOrderId());
            return ResponseData.error(CommonEnum.QUERY_ERROR_NODATA);
        }
        order.setOrderState(orderStateDto.getState());
        order.setUpdateTime(new Date());
        boolean flag = orderService.updateById(order);
        return flag ? ResponseData.success(CommonEnum.OPERATION_SUCCESS) : ResponseData.error(CommonEnum.OPERATION_ERROR);
    }
    //endregion

    //region 校验订单

    /**
     * 校验订单
     *
     * @param orderEntity 订单对象
     * @return
     */
    public String checkOrder(OrderEntity orderEntity){
        try {
            if(orderEntity.getProductId() == null){
                return "产品id不能为空";
            }
            if(StringUtils.isBlank(orderEntity.getOrderState())){
                return "订单状态不能为空";
            }
            if(orderEntity.getProposalId() == null){
                return "投保单id不能为空";
            }
            if(orderEntity.getCaseId() == null){
                return "方案id不能为空";
            }
            //通过投保单主键查询投保单
            ProposalEntity proposalEntity = proposalService.getById(orderEntity.getProposalId());
            if(proposalEntity == null){
                return "投保单不存在";
            }
            orderEntity.setProposalNo(proposalEntity.getProposalNo());
            //通过产品主键查询产品
            ProductEntity product = productService.getById(orderEntity.getProductId());
            if(product == null){
                return "产品不存在";
            }
            orderEntity.setProductName(product.getProductName());
            List<ProductCaseEntity> productCaseEntityList = productCaseService.queryListByProductId(orderEntity.getProductId());
            if(CollectionUtils.isEmpty(productCaseEntityList)){
                return "方案不存在";
            }
            List<String> caseIdList = productCaseEntityList.stream().map(ProductCaseEntity::getCaseId).collect(Collectors.toList());
            if(!caseIdList.contains(orderEntity.getCaseId())){
                return "方案不在此产品中";
            }
            for(ProductCaseEntity productCaseEntity : productCaseEntityList){
                if(orderEntity.getCaseId().equals(productCaseEntity.getCaseId())){
                    orderEntity.setCaseName(productCaseEntity.getCaseName());
                    orderEntity.setCasePrice(String.valueOf(productCaseEntity.getCasePrice()));
                    break;
                }
            }
            orderEntity.setOrderNo(NumberUtils.generateOrderNo(product.getProductCode()));
            if(orderEntity.getCreateTime() == null){
                orderEntity.setCreateTime(new Date());
            }
            return ConstantFlag.TRUE_STR;
        } catch (Exception e) {
            log.error("【校验订单数据异常】", e);
            return "数据校验异常";
        }
    }
    //endregion

    /**
     * 保存订单
     *
     * @param orderFormDto
     * @return
     */
    @ApiOperation(value = "修改订单")
    @PostMapping("/editOrder")
    public ResponseData editOrder(@RequestBody OrderFormDto orderFormDto, @RequestHeader(value = "Authorization") String token, @RequestHeader String userToken){
        try {
            if(!JwtOperatorUtil.validateToken(userToken)){
                return ResponseData.error(CommonEnum.USER_TOKEN_ERROR);
            }
            String orderId = orderFormDto.getOrderId();
            if(orderId == null){
                log.error("【修改订单失败, 订单不存在】");
                return ResponseData.error("订单id不能为空 ");
            }
            OrderEntity orderEntity = new OrderEntity();
            BeanUtils.copyProperties(orderFormDto, orderEntity);
            String checkOrder = checkOrder(orderEntity);
            if(!ConstantFlag.TRUE_STR.equals(checkOrder)){
                log.error("【修改订单失败, {}】", checkOrder);
                return ResponseData.error(checkOrder);
            }
            String userId = JwtOperatorUtil.getUserId(userToken);
            orderEntity.setUpdateTime(new Date());
            orderEntity.setUpdatePersonId(userId);
            boolean flag = orderService.updateById(orderEntity);
            return flag ? ResponseData.success(orderEntity.getOrderId()) : ResponseData.error(CommonEnum.UPDATE_ERROR);
        } catch (BeansException e) {
            log.error("【修改订单失败, 系统异常】", e);
            return ResponseData.error(CommonEnum.SYSTEM_ERROR);
        }
    }

    //region 删除订单

    /**
     * 删除订单
     *
     * @param orderId 订单id
     * @param token 合作方凭证
     * @param userToken 用户凭证
     * @return
     */
    @ApiOperation(value = "删除订单")
    @PostMapping("/removeOrder")
    public ResponseData removeOrder(@RequestBody String orderId, @RequestHeader(value = "Authorization") String token, @RequestHeader String userToken){
        try {
            if(!JwtOperatorUtil.validateToken(userToken)){
                return ResponseData.error(CommonEnum.USER_TOKEN_ERROR);
            }
            OrderEntity orderEntity = orderService.getById(orderId);
            if(orderEntity == null){
                log.error("【删除订单失败, 订单不存在：{}】", orderId);
                return ResponseData.error(CommonEnum.QUERY_ERROR_NODATA);
            }
            orderEntity.setDeleteFlag(String.valueOf(DeleteFlagEnum.DELETE.getCode()));
            orderEntity.setUpdateTime(new Date());
            orderEntity.setUpdatePersonId(JwtOperatorUtil.getUserId(userToken));
            boolean flag = orderService.updateById(orderEntity);
            return flag ? ResponseData.success(CommonEnum.OPERATION_SUCCESS) : ResponseData.error(CommonEnum.OPERATION_ERROR);
        } catch (Exception e) {
            log.error("【删除订单失败, 系统异常】", e);
            return ResponseData.error(CommonEnum.SYSTEM_ERROR);
        }
    }
    //endregion

}
